#coding=utf-8
import arcpy
import math

path = r'D:\WorkData\20250712四川河流\0820处理'
arcpy.env.workspace = path
arcpy.env.overwriteOutput = True
spatial_ref = arcpy.SpatialReference(4326)

rivs1 = r'D:\WorkData\20250712四川河流\0820处理\rivs1.shp'.decode('utf-8')
#c_flowId:需要加点的河流id
c_flowId = 3
cs1 = arcpy.da.SearchCursor(rivs1,['SHAPE@','flowId'])
lpList = []
for row1 in cs1:
    if row1[1] == c_flowId:
       lpList.append(row1[0].lastPoint)
cs1.reset()

j = 0
for lp in lpList:
    geo_lp = arcpy.PointGeometry(lp,spatial_ref)

    expression = "rivId = '{}'".format(c_flowId)
    cs2 = arcpy.da.SearchCursor(rivs1, ['SHAPE@WKT'], where_clause=expression)
    WKT = [row[0] for row in cs2][0]
    cs2.reset()
    dis = 1
    insIndex = 0
    cs3 = arcpy.da.SearchCursor(rivs1, ['SHAPE@','SHAPE@WKT'],where_clause=expression,explode_to_points=True)
    i = 0
    for row3 in cs3:
        if geo_lp.distanceTo(row3[0]) < dis:
            insIndex = i
            dis = geo_lp.distanceTo(row3[0])
        i += 1
    print j,insIndex,dis
    cs3.reset()

    pointList = WKT.split('((')[1].split('))')[0].split(', ')

    x1 = float(pointList[insIndex].split(' ')[0])
    y1 = float(pointList[insIndex].split(' ')[1])
    x2 = float(pointList[insIndex - 1].split(' ')[0])
    y2 = float(pointList[insIndex - 1].split(' ')[1])

    segmentLength = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
    pointX = geo_lp.centroid.X
    pointY = geo_lp.centroid.Y
    pToSegmentSP = math.sqrt((pointX - x2) ** 2 + (pointY - y2) ** 2)
    if (segmentLength > pToSegmentSP):
        pointList.insert(insIndex, ('%.15f %.15f' % (pointX, pointY)).decode('utf8'))
    else:
        pointList.insert(insIndex + 1, ('%.15f %.15f' % (pointX, pointY)).decode('utf8'))

    with arcpy.da.UpdateCursor(rivs1, 'SHAPE@WKT', where_clause=expression) as yb:
        for row in yb:
            N_WKT = 'MULTILINESTRING ((%s))' % ','.join(pointList)
            row[0] = N_WKT
            yb.updateRow(row)
    j += 1